﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using AdvCMS.Models;
using AdvCMS.Data.Repositories;
using AdvCMS.Data;

namespace AdvCMS.Services
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AuthenicationService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [WebGet(ResponseFormat=WebMessageFormat.Json)]
        [OperationContract]

        public SessionKeyDTO Authenicate(string username, string password)
        {
            Factory.RepositoryFactory factory = new Factory.RepositoryFactory();
            IUserRepository repository = factory.NewUserRepository();
            AdvCMS.Models.SessionKeyDTO dto = new SessionKeyDTO();
            IAdvUser user = repository.GetByUserName(username);
            if (user !=null&&user.Password == password)
            {
                dto.Key = Guid.NewGuid().ToString();
                dto.ExpireDate = DateTime.Now.AddHours(2);
                user.SessionKey = new Guid(dto.Key);
                user.KeyExpireDate = dto.ExpireDate;
                repository.Update();
            }
            else
            {
                dto.Key = "";
                dto.ExpireDate = DateTime.Now;
            }
            return dto;
        }

    
    }
}
